<template>
  <div class="TaskPlanningList">
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-form
            class="form"
            ref="form"
            :model="search"
            label-width="80px"
            :inline="true"
          >
            <el-form-item label="任务名称">
              <el-input
                maxlength="20"
                show-word-limit
                v-model="search.planName"
              ></el-input>
            </el-form-item>
            <el-form-item label="任务状态">
              <el-select
                v-model="search.planStatus.value"
                placeholder="请选择任务状态"
                @change="statusChange"
              >
                <el-option
                  v-for="item in search.planStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button @click="resize">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-card class="el-card" shadow="never">
          <el-table :data="taskList" height="500" style="width: 100%">
            <el-table-column fixed prop="id" label="ID" width="60">
            </el-table-column>

            <el-table-column
              fixed
              prop="planName"
              label="任务计划名称"
              width="200"
            >
            </el-table-column>
            <el-table-column sortable label="开始时间" width="160">
              <template slot-scope="scope">{{
                scope.row.planStartTime | formatDate
              }}</template>
            </el-table-column>
            <el-table-column sortable label="结束时间" width="160">
              <template slot-scope="scope">{{
                scope.row.planEndTime | formatDate
              }}</template>
            </el-table-column>

            <el-table-column label="任务状态" width="80">
              <template slot-scope="scope">
                {{ planStatusCn(scope.row.planStatus) }}
              </template></el-table-column
            >
            <el-table-column prop="planRequire" label="采集要求">
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="250">
              <template slot="header">
                <CreateTask
                  :loading="loading"
                  label="创建任务计划"
                  @success="getList"
                  type="primary"
                ></CreateTask>
              </template>

              <template slot-scope="scope">
                <!-- //  1:未发布 = 发布 2:已发布 = 撤回 3:已撤回 = 发布 4:已启用 = 停用 5：已停用 = 启用 -->

                <!-- <el-button type="text" size="small">发布{{scope.row.planStatus}}</el-button> -->
                <el-button
                  type="text"
                  size="small"
                  :loading="loading"
                  v-if="
                    scope.row.planStatus === 1 ||
                    scope.row.planStatus === 3 ||
                    scope.row.planStatus === 5
                  "
                  @click="updateStatus(scope.row, 2, '发布')"
                  >发布</el-button
                >
                <el-button
                  v-else
                  :loading="loading"
                  type="text"
                  size="small"
                  @click="updateStatus(scope.row, 3, '撤回')"
                  >撤回</el-button
                >

                <!--   v-if="scope.row.planStatus === 2 || scope.row.planStatus === 4
                  " -->
                <el-button
                  v-if="false"
                  type="text"
                  :loading="loading"
                  size="small"
                  @click="updateStatus(scope.row, 5, '停用')"
                  >停用</el-button
                >

                <el-button
                  v-if="false"
                  :loading="loading"
                  type="text"
                  size="small"
                  @click="updateStatus(scope.row, 4, '启用')"
                  >启用</el-button
                >

                <el-button
                  :loading="loading"
                  @click="showClick(scope.row.id)"
                  type="text"
                  size="small"
                  >查看</el-button
                >
                <el-button
                  :loading="loading"
                  type="text"
                  @click="handleClick(scope.row.id)"
                  size="small"
                  >编辑</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="bottom">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="currentchange"
              :current-page="paging.pageNum"
              :page-sizes="[5, 10, 20, 30, 40]"
              :page-size="paging.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="paging.total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- :before-close="handleClose" -->
    <el-dialog
      :title="details.planName"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        :disabled="disabled"
        :rules="rules"
        :model="details"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item prop="planName" label="计划名称">
          <el-input
            v-model="details.planName"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="采集时间" required>
          <el-col :span="11">
            <el-form-item prop="planStartTime">
              <el-date-picker
                type="datetime"
                placeholder="采集任务开始时间"
                v-model="details.planStartTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center">-</el-col>
          <el-col :span="11">
            <el-form-item prop="planEndTime" required>
              <el-date-picker
                type="datetime"
                placeholder="采集任务结束时间"
                v-model="details.planEndTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <!-- <el-form-item label="任务状态" prop="planStatus">
                    <template v-for="(item, index) in search.planStatus">
                        <el-radio v-if="index != 0" :key="index" v-model="details.planStatus" :label="item.value">{{ item.label }}</el-radio>
                    </template>
                </el-form-item> -->

        <el-form-item label="采集区域" prop="area">
          <el-col :span="18">
            <div class="block">
              <el-cascader
                v-model="area"
                type="primary"
                :options="options"
                :props="props"
                collapse-tags
                @change="changecollectTaskTown"
              ></el-cascader>
              <el-button
                type="primary"
                style="margin-left: 20px"
                @click="selectAll"
                >全选</el-button
              >
              <el-button
                type="primary"
                style="margin-left: 10px"
                @click="selectNone"
                >取消全选</el-button
              >
            </div>
          </el-col>
        </el-form-item>

        <el-form-item label="采集要求" required prop="planRequire">
          <el-input
            type="textarea"
            class="textarea"
            maxlength="255"
            show-word-limit
            v-model="details.planRequire"
          ></el-input>
        </el-form-item>

        <el-form-item label="图片" v-if="disabled">
          <div class="imgList">
            <el-image
              class="img"
              v-for="item in details.ossImgList"
              :key="item.id"
              :src="item.imgUrl"
            ></el-image>
          </div>
        </el-form-item>
        <el-form-item label="图片" v-else>
          <Upload
            label="通知/图片"
            v-if="details.ossImgList instanceof Array"
            :imglist="details.ossImgList"
            @click="getUrlList"
          ></Upload>
          <Upload
            label="通知/图片"
            v-else
            :imglist="[]"
            @click="getUrlList"
          ></Upload>
        </el-form-item>

        <el-form-item label="">
          <el-button
            type="primary"
            v-if="showButton"
            @click="editDetails('ruleForm')"
            >确 定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from "@/library";
import { mapGetters } from "vuex";
import { convertKey, editDisplay } from "@/library";
import areaList from "@/areaList.js";
export default {
  name: "TaskPlanningList",
  data() {
    var VerifyplanStartTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请选择采集开始的时间"));
      } else {
        callback();
      }
    };

    var VerifyplanEndTime = (rule, value, callback) => {
      if (value) {
        let planStartTime = +new Date(this.details.planStartTime);
        let planEndTime = +new Date(value);
        if (planEndTime - planStartTime <= 0) {
          callback(new Error("结束时间不能小于开始时间"));
        } else {
          this.details.planEndTime = value;
          callback();
        }
      } else {
        callback(new Error("请选择采集结束的时间"));
      }
    };

    var VerifyArea = (rule, value, callback) => {
      let area = this.area;
      setTimeout(() => {
        if (area instanceof Array) {
          callback();
        } else {
          callback(new Error("您必须选择一个采集镇街"));
        }
      }, 1000);
    };

    return {
      notify: 15,
      loading: false,
      areaList: areaList,
      treeDataProps: {
        children: "children",
        value: "administrativeCode",
        label: "administrativeName",
      },
      area: [],
      props: {
        multiple: true,
      },
      ruleForm: {},
      search: {
        planName: "",
        planStatus: [
          {
            value: "",
            label: "全部",
          },
          {
            value: 1,
            label: "未发布",
          },
          {
            value: 2,
            label: "已发布",
          },
          {
            value: 3,
            label: "已撤回",
          },
          // ,
          // {
          //   value: 4,
          //   label: "已启用",
          // },
          // {
          //   value: 5,
          //   label: "已停用",
          // },
        ],
        value: "",
      },
      params: {
        pageNumber: 1,
        pageSize: 10,
      },
      paging: {},
      taskList: [],
      dialogVisible: false,
      details: {
        info: {},
        area: "",
        planType: "",
      },
      villageMatch: [],
      townMatch: [],
      townVillage: {},
      townVillageCopy: {},
      disabled: true,
      showButton: false,
      rules: {
        planName: [
          {
            required: true,
            message: "请输入采集任务名称",
            trigger: "blur",
          },
        ],
        planStartTime: [
          {
            type: "date",
            validator: VerifyplanStartTime,
            message: "请输入开始采集时间",
            required: true,
            trigger: "change",
          },
        ],

        planEndTime: [
          {
            type: "date",
            validator: VerifyplanEndTime,
            message: "请输入结束采集时间",
            required: true,
            trigger: "change",
          },
        ],

        area: [
          {
            type: "array",
            validator: VerifyArea,
            message: "采集区域不能为空",
            required: true,
            trigger: "change",
          },
        ],

        planRequire: [
          {
            required: true,
            message: "采集要求不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.queryPlanAccordingToTheTask();
    this.villageInit();
  },
  computed: {
    ...mapGetters({
      options: "getTreeData/filtersVillage",
    }),
  },
  methods: {
    resize(){
       this.getList();
       this.search = {
        planName: "",
        planStatus: [
          {
            value: "",
            label: "全部",
          },
          {
            value: 1,
            label: "未发布",
          },
          {
            value: 2,
            label: "已发布",
          },
          {
            value: 3,
            label: "已撤回",
          },
          // ,
          // {
          //   value: 4,
          //   label: "已启用",
          // },
          // {
          //   value: 5,
          //   label: "已停用",
          // },
        ],
        value: "",
      }
    },
    selectAll() {
      this.area = this.areaList;
      this.changecollectTaskTown(this.area);
    },
    selectNone() {
      this.area = [];
      this.townVillage = {};
    },
    getUrlList(arr) {
      this.details.planFiles = arr.join(",");
    },
    getList() {
      this.queryPlanAccordingToTheTask();
    },
    // handleClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then(() => {
    //       done();
    //     })
    //     .catch(() => {});
    // },
    statusChange(item) {
      console.log(item);
      if (typeof item === "number") {
        this.params.status = item;
      } else {
        delete this.params.status;
      }
    },
    planStatusCn(index) {
      var planStatus = {
        1: "未发布",
        2: "已发布",
        3: "已撤回",
        4: "已启用",
        5: "已停用",
      };

      return planStatus[index];
    },

    updateStatus(row, planStatus, text) {
      this.$confirm("此操作将" + text + "计划, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;

          let notify;
          setTimeout(() => {
            notify = this.$notify.warning({
              title: "消息",
              message:
                "当前操作可能需要较长时间，如果长时间未" +
                text +
                "成功，您可以离开当前页面，先进行其他事情，任务会转入后台继续静默执行",
              duration: 35000,
            });
          }, 0);

          let url = "task/task/updateStatus";
          this.$axios
            .post(url, {
              params: {
                id: row.id,
                planStatus,
              },
            })
            .then((res) => {
              if (res.result === "success") {
                this.loading = false;
                this.queryPlanAccordingToTheTask(this.params).then(() => {
                  notify.close();
                  this.$message({
                    type: "success",
                    message: "计划" + text + "成功",
                  });
                });
              }
            });
        })
        .catch((error) => {
          console.log(error);
          this.loading = false;
          this.$message({
            type: "info",
            message: "已取消" + text,
          });
        });
    },
    closeDetails() {
      this.dialogVisible = false;
    },
    editDetails(formName) {
      if (!localStorage.getItem("SYS_TYPE")) {
        this.$message.error("系统异常，请退出重新登录");
        return false;
      }
      if (Object.keys(this.townVillage).length === 0) {
        this.changecollectTaskTown(this.area);
        console.log(this.townVillage);
      }

      this.details.planType = localStorage.getItem("SYS_TYPE");
      //修改计划提交

      this.$refs[formName].validate((valid) => {
        // console.log(valid)
        if (valid) {
          if (Object.keys(this.townVillage).length === 0) {
            this.$message({
              type: "warning",
              message: "采集区域镇街信息不能为空",
              duration: 2500,
            });
            return false;
          }

          this.$axios
            .post("task/task/update", {
              params: {
                id: this.details.id,
                planName: this.details.planName,
                planStatus: this.details.planStatus,
                area: JSON.stringify(this.townVillage),
                planRequire: this.details.planRequire,
                planStartTime: formatDate(this.details.planStartTime),
                planEndTime: formatDate(this.details.planEndTime),
                planFiles: this.details.planFiles,
                planType: this.details.planType,
              },
            })
            .then((res) => {
              if (res.errorCode === "00000") {
                this.$message.success(res.errorMsg);
                this.queryPlanAccordingToTheTask();
                this.dialogVisible = false;
              } else {
                this.$message.warning(res.errorMsg);
              }
            });
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    villageInit() {
      this.options.forEach((item) => {
        this.townMatch.push(item.value);
        this.villageMatch.push([
          ...JSON.stringify([item.children]).match(/\d{12}/g),
        ]);
      });
    },
    changecollectTaskTown(e) {
      this.townVillage = {};
      let newSelect = new Map();
      for (let index = 0; index < e.length; index++) {
        const item = e[index];

        let town, townIndex, villageIndex;
        if (this.townMatch) {
          townIndex = this.townMatch.indexOf(item[0]);
        }
        if (this.townMatch) {
          villageIndex = this.villageMatch[townIndex].indexOf(item[1]);
        }
        town = JSON.parse(JSON.stringify(this.options[townIndex]));

        if (typeof this.villageMatch[townIndex][villageIndex] === "undefined") {
          console.log(
            this.villageMatch[townIndex] +
              ">>>>>" +
              this.villageMatch[townIndex][villageIndex]
          );
          continue;
        } else {
          town.children = [
            JSON.parse(
              JSON.stringify(this.villageMatch[townIndex][villageIndex])
            ),
          ];
        }
        if (newSelect.get(town.value)) {
          newSelect.get(town.value).children = [
            ...newSelect.get(town.value).children,
            ...town.children,
          ];
        } else {
          newSelect.set(town.value, town);
        }
      }
      newSelect.forEach((item, key) => {
        // newSelectTown.push(item);
        this.townVillage[key] = item.children;
      });
      // console.log(this.townVillage);
      // this.townVillage = newSelectTown;
    },
    showClick(id) {
      this.loading = true;
      this.handleClick(id);
      this.disabled = true;
    },
    handleClick(id) {
      this.loading = true;
      this.disabled = false;
      this.showButton = true;
      this.$axios
        .get("task/task/getAListOfPlans/", {
          params: {
            "planInfo.id": id,
          },
        })
        .then((res) => {
          this.loading = false;
          let treeData;
          this.details = res.data.list[0];
          if (this.details) {
            if (this.details.treeData) {
              if (this.details.treeData.treeItem[0]) {
                treeData = this.details.treeData.treeItem[0].children;
              }
            }
          }
          let options;
          if (typeof treeData != "undefined") {
            options = convertKey(treeData, {
              administrativeName: "label",
              administrativeCode: "value",
            });
            this.details.options = options;
          } else {
            this.details.options = [];
          }
          // console.log(JSON.stringify(options,['label','value','children'])
          //构建 areas 回显数据

          this.area = editDisplay(this.details.treeData.list);
          console.log(this.area);
          delete this.details.treeData;
          this.dialogVisible = true;
        });
    },
    onSearch() {
      this.params.keywords = this.search.planName;
      this.queryPlanAccordingToTheTask(this.params);
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.queryPlanAccordingToTheTask(this.params);
    },
    currentchange(pageNumber) {
      this.params.pageNumber = pageNumber;
      this.queryPlanAccordingToTheTask(this.params);
    },
    queryPlanAccordingToTheTask(params) {
      return this.$fishing.queryPlanAccordingToTheTask(params).then((res) => {
        this.taskList = res.data.list;
        delete res.data.list;
        this.paging = res.data;
        return Promise.resolve(res);
      });
    },
  },
};
</script>

<style lang="scss">
.TaskPlanningList {
  .form {
    padding: 15px 10px;
  }

  .imgList {
    display: flex;
    justify-content: flex-start;

    .img {
      width: 150px;
      height: 150px;
      margin: 15px;
    }
  }

  .el-card {
    width: 98%;
    margin: 15px auto 0;

    .bottom {
      display: flex;
      justify-content: flex-end;
      margin-top: 15px;
    }
  }
}
</style>
